package com.yj.springbootstudy.mulThread.demo;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 多线程模拟售票
 */
public class SellTicketDemo {
    public static void main(String[] args) throws InterruptedException {

        TicketWindow ticketWindow = new TicketWindow(1000);
        //用于存储买票的数量
        List<Integer> sumCount = new ArrayList<>();
        //用于存储买票的线程
        List<Thread> threadList = new ArrayList<>();
        //多线程模拟买票
        for (int i = 0;i<4000;i++){

            Thread thread = new Thread(() -> {

                Integer amount = ticketWindow.sell(new Random().nextInt(5) + 1);
                sumCount.add(amount);
            });
            threadList.add(thread);
            thread.start();

        }
        for (Thread thread : threadList) {
            thread.join();
        }
        Integer count = ticketWindow.getCount();
        Integer sum = sumCount.stream().mapToInt(value -> value).sum();
        System.out.println("余票："+count);
        System.out.println("售出的票："+sum);

    }
}

class TicketWindow{
    private static Integer count; //票的数量

    public TicketWindow(int count){
        this.count = count;
    }

    public Integer getCount(){
        return this.count;
    }

    public Integer sell(int amount){
        if (count >= amount){
            count -= amount;
            return amount;
        }else {
            return 0;
        }
    }


}
